package cn.codeforfun.interceptor.adapter;

import cn.codeforfun.common.WechatService;
import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.follower.Follower;
import cn.codeforfun.follower.FollowerService;
import cn.codeforfun.interceptor.OauthInterceptor;
import cn.codeforfun.utils.UrlUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/17 0017.
 */
public class OauthInterceptorAdapter implements HandlerInterceptor {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private FollowerService followerService;
    private Logger log = Logger.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        if (o instanceof HandlerMethod) {//java.lang.ClassCastException: org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) o;
            Method method = handlerMethod.getMethod();
            //获取方法级拦截器注解
            OauthInterceptor annotation = method.getAnnotation(OauthInterceptor.class);
            //获取类级别拦截器注解
            OauthInterceptor annotation1 = ((HandlerMethod) o).getBean().getClass().getAnnotation(OauthInterceptor.class);
            if (annotation != null || annotation1 != null) {
                HttpSession session = request.getSession();
                if (session.getAttribute(SessionConsts.OPEN_ID) != null) {
                    log.info("openId:-----------" + session.getAttribute(SessionConsts.OPEN_ID));
                    return true;
                } else if (StringUtils.isNotEmpty(request.getParameter("code"))) {
                    String code = request.getParameter("code");
                    log.info("code:-----------" + code);
                    Follower follower = followerService.snsFollower(code);
                    String openId = follower.getOpenId();
                    session.setAttribute(SessionConsts.OPEN_ID, openId);
                    response.sendRedirect(getRedirectUrl(request));
                    return false;
                } else {
                    response.sendRedirect(getRedirectUrl(request));
                    return false;
                }
            }
        }
        // 没有注解通过拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public String getRedirectUrl(HttpServletRequest request) throws IOException {
        String param = request.getQueryString();
        if (StringUtils.isNotEmpty(param)) {
            Map paramMap = UrlUtil.getUrlParams(param);
            if (paramMap.containsKey("code")) {
                paramMap.remove("code");
            }
            param = UrlUtil.getUrlParamsByMap(paramMap);
        } else {
            param = null;
        }
        String redirectUrl = String.valueOf(request.getRequestURL() + (StringUtils.isEmpty(param) ? "" : "?" + param));
        String state = request.getParameter("state");
        WxMpService service = wechatService.getService();
        String snsapi_userinfo = service.oauth2buildAuthorizationUrl(redirectUrl, "snsapi_userinfo", state);
        System.out.println(snsapi_userinfo);
        return snsapi_userinfo;
    }
}
